package com.ctshk.rpc.order.custom.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.GlobalConstants;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.NumberConstant;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.req.MainData;
import com.ctshk.common.utils.CharUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.common.vo.MainDataCount;
import com.ctshk.rpc.custom.dto.trip.*;
import com.ctshk.rpc.custom.req.trip.CustomizedTripScheduleDTO;
import com.ctshk.rpc.custom.req.trip.TripScheduleAmountStatisticsReq;
import com.ctshk.rpc.custom.req.trip.TripScheduleListIdReq;
import com.ctshk.rpc.custom.req.trip.TripScheduleTouristCountReq;
import com.ctshk.rpc.custom.service.ICustomizedTripScheduleAmountStatisticsService;
import com.ctshk.rpc.custom.service.ICustomizedTripScheduleService;
import com.ctshk.rpc.custom.service.ICustomizedTripScheduleTouristCountService;
import com.ctshk.rpc.order.custom.dto.order.*;
import com.ctshk.rpc.order.custom.entity.*;
import com.ctshk.rpc.order.custom.mapper.*;
import com.ctshk.rpc.order.custom.req.order.CustomOrderIdReq;
import com.ctshk.rpc.order.custom.req.order.CustomOrderListReq;
import com.ctshk.rpc.order.custom.req.order.CustomOrderUpdateContactReq;
import com.ctshk.rpc.order.custom.req.schedule.*;
import com.ctshk.rpc.order.custom.service.*;
import com.ctshk.rpc.order.custom.util.OrderUtil;
import com.ctshk.rpc.order.custom.vo.TouristCollectionFeeJson;
import com.ctshk.rpc.order.custom.vo.TouristTypeNum;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.IMainDataCurrencyService;
import com.ctshk.rpc.system.service.ISysDepartmentService;
import com.ctshk.rpc.system.service.ISysPermissionService;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 定制包团订单 服务实现类
 * </p>
 *
 * @author 叶冠峰
 * @since 2021-02-22
 */
@DubboService
public class CustomizedOrderServiceImpl extends ServiceImpl<CustomizedOrderMapper, CustomizedOrder> implements ICustomizedOrderService {

    @DubboReference
    private ICustomizedTripScheduleService tripScheduleService;
    @DubboReference
    private ISysUserService sysUserService;
    @DubboReference
    private ISysDepartmentService sysDepartmentService;
    @DubboReference
    private ISysPermissionService sysPermissionService;
    @DubboReference
    private ICustomizedTripScheduleAmountStatisticsService tripScheduleAmountStatisticsService;
    @DubboReference
    private INumberService numberService;
    @DubboReference
    private ICustomizedTripScheduleTouristCountService tripScheduleTouristCountService;
    @DubboReference
    private IMainDataCurrencyService mainDataCurrencyService;

    private ICustomizedOrderDiscountService orderDiscountService;

    private ICustomizedOrderTouristInfoService orderTouristInfoService;

    private ICustomizedOrderTouristPriceService orderTouristPriceService;


    @Autowired
    private CustomizedOrderMapper orderMapper;
    @Autowired
    private CustomizedOrderAmountStatisticsMapper orderAmountStatisticsMapper;
    @Autowired
    private CustomizedOrderTouristInfoMapper orderTouristInfoMapper;
    @Autowired
    private CustomizedOrderTouristPriceMapper orderTouristPriceMapper;



    /**
     * 定制包团下单
     *
     * @param req
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result createOrder(TripScheduleCreateOrderReq req, Long userId) {
        //获取团期信息
        CustomizedTripScheduleDTO tripSchedule = tripScheduleService.queryByScheduleId(req.getScheduleId());
        if (tripSchedule == null){
            throw new BusinessException(SystemError.CUSTOM_3006);
        }
        //TODO 团期状态待确认
        /*if (tripSchedule.getGroupStatus().intValue() != NumberConstant.TWO.getValue() && tripSchedule.getGroupStatus().intValue() != NumberConstant.FIVE.getValue()){
            throw new BusinessException(SystemError.CUSTOM_3012);
        }*/
        //判断报价方式
        if (Objects.equals(req.getQuotationType(),NumberConstant.ONE.getValue())){
            //自由报价
            List<FreeQuoteReqPackageReq> reqPackages = req.getReqPackages();
            List<TouristTypePriceReq> quotationTouristTypeDTOS = reqPackages.get(0).getQuotationTouristTypeDTOS();
            List<QuotationTouristTypeReq> touristTypes = new ArrayList<>();
            //查询统计团期旅客类型人数
            for (int i=0;i<quotationTouristTypeDTOS.size();i++){
                QuotationTouristTypeReq quotationTouristTypeReq = EntityUtil.copy(quotationTouristTypeDTOS.get(i),QuotationTouristTypeReq.class);
                //遍历所有套餐
                for (FreeQuoteReqPackageReq reqPackageReq : reqPackages){
                    List<TouristTypePriceReq> packageTouristTypes = reqPackageReq.getQuotationTouristTypeDTOS();
                    for (TouristTypePriceReq touristTypeReq : packageTouristTypes){
                        //按旅客类型主数据ID分类
                        if (quotationTouristTypeReq.getValue().longValue() == touristTypeReq.getValue().longValue()){
                            quotationTouristTypeReq.setPeopleNum(touristTypeReq.getPeopleNum());
                            break;
                        }
                    }
                }
                if (quotationTouristTypeReq.getPeopleNum() > 0){
                    touristTypes.add(quotationTouristTypeReq);
                }
            }
            //保存团期旅客统计（该数据自由报价前端没有传，需自己统计）
            req.setTouristTypes(touristTypes);
        }
        //订单
        CustomizedOrder order = new CustomizedOrder();
        order.setId(SnowflakeIdWorker.nextId());
        order.setScheduleId(req.getScheduleId());
        order.setOrderSource(1);
        /**
         * 联络人
         */
        order.setContactCnName(req.getContactReq().getContactCnName());
        order.setContactCnSurname(req.getContactReq().getContactCnSurname());
        order.setContactEnName(req.getContactReq().getContactEnName());
        order.setContactEnSurname(req.getContactReq().getContactEnSurname());
        order.setContactEmail(req.getContactEmail());
        order.setContactGender(req.getContactGender());
        order.setContactTelephones(req.getContactTelephones());
        order.setInternalRemark(req.getInternalRemark());
        /**
         * 客户信息
         */
        order.setCustomerType(req.getCustomerTypeReq().getCustomerType());
        if (req.getCustomerTypeReq().getCustomerType().intValue() == NumberConstant.TWO.getValue()){
            //大客户
            if (req.getCustomerTypeReq().getBigClientId() == null || StringUtils.isBlank(req.getCustomerTypeReq().getBigClientName())){
                return Result.failed(new BusinessException(SystemError.SYS_409,"大客户"));
            }
            order.setBigClientId(req.getCustomerTypeReq().getBigClientId());
            order.setBigClientName(req.getCustomerTypeReq().getBigClientName());
        }
        /**
         * 统计
         */
        //旅客信息
        List<QuotationTouristTypeReq> touristList = req.getTouristTypes();
        List<TripScheduleTouristCountReq> countReqList = new ArrayList<>();
        //团期剩余人数统计
        List<TripScheduleTouristCountDTO> countDTOList = tripScheduleTouristCountService.queryBySchedule(req.getScheduleId());
        for (QuotationTouristTypeReq touristTypeReq : touristList){
            if (countDTOList != null && countDTOList.size() > 0){
                for (TripScheduleTouristCountDTO countDTO : countDTOList){
                    if (countDTO.getTouristTypeId().longValue() == touristTypeReq.getValue().longValue()){
                        //该旅客类型剩余可下单人数
                        int remainPeople = countDTO.getTotalPeople() - countDTO.getOrderPeople();
                        if (touristTypeReq.getPeopleNum().intValue() > remainPeople){
                            throw new BusinessException(SystemError.CUSTOM_ORDER_4031,touristTypeReq.getLabel());
                        }
                        TripScheduleTouristCountReq countReq = new TripScheduleTouristCountReq();
                        countReq.setId(countDTO.getId());
                        if (countDTO.getOrderPeople() == null){
                            countDTO.setOrderPeople(0);
                        }
                        countReq.setOrderPeople(countDTO.getOrderPeople() + touristTypeReq.getPeopleNum());
                        countReq.setModifiedId(userId);
                        countReqList.add(countReq);
                        break;
                    }
                }
            }
        }
        if (countReqList.size() > 0){
            //更新统计
            boolean batchUpdate = tripScheduleTouristCountService.batchUpdate(countReqList);
            if (!batchUpdate){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //总金额
        BigDecimal totalPrice = BigDecimal.ZERO;
        //总套餐金额
        BigDecimal totalTourFee = BigDecimal.ZERO;
        //旅客总人数
        Integer totalPeople = 0;
        //旅客总代收费用
        BigDecimal totalCollectionFee = BigDecimal.ZERO;
        //游客信息
        List<CustomizedOrderTouristInfo> touristInfoList = new ArrayList<>();
        //定制包团订单游客自由报价
        List<CustomizedOrderTouristPrice> orderTouristPriceList = new ArrayList<>();
        //旅客类型代收费用
        List<CollectionTouristPriceDTO> collectionTouristList = tripSchedule.getCollectionTouristList();
        for (QuotationTouristTypeReq tourist : touristList){
            totalPeople += tourist.getPeopleNum();
            if (CollectionUtils.isNotEmpty(collectionTouristList)){
                for (CollectionTouristPriceDTO collectionPrice : collectionTouristList){
                    if (collectionPrice.getTouristTypeId().longValue() == tourist.getValue().longValue()){
                        totalCollectionFee = totalCollectionFee.add(collectionPrice.getPrice().multiply(new BigDecimal(tourist.getPeopleNum())));
                        break;
                    }
                }
            }
        }
        order.setTotalPeople(totalPeople);
        /**
         * 套餐报价
         */
        order.setSchedulePriceType(tripSchedule.getQuotationType());
        //计算套餐总价
        //调整费用
        BigDecimal adjustmentCost = getAdjustmentFee(tripSchedule.getFeeAdjustList());
        //报价方式
        if (tripSchedule.getQuotationType().intValue() == NumberConstant.ONE.getValue()){
            //自由报价
            List<FreeQuoteReqPackageReq> reqPackages = req.getReqPackages();
            for (FreeQuoteReqPackageReq reqPackage : reqPackages){
                //旅客价格信息
                List<TouristTypePriceReq> touristTypePriceList = reqPackage.getQuotationTouristTypeDTOS();
                for (TouristTypePriceReq touristPrice : touristTypePriceList){
                    if (touristPrice.getPeopleNum() > 0){
                        //获取团期加幅后团费
                        BigDecimal groupAddFee = tripScheduleService.getScheduleAddAmount(touristPrice.getPrice(),req.getScheduleId(),userId);
                        totalTourFee = totalTourFee.add(groupAddFee.multiply(new BigDecimal(touristPrice.getPeopleNum())));
                        for (int i=0;i<touristPrice.getPeopleNum();i++){
                            //旅客信息
                            CustomizedOrderTouristInfo touristInfo = new CustomizedOrderTouristInfo();
                            touristInfo.setId(SnowflakeIdWorker.nextId());
                            touristInfo.setOrderId(order.getId());
                            touristInfo.setScheduleId(req.getScheduleId());
                            touristInfo.setPackageId(reqPackage.getId());
                            touristInfo.setPackageName(reqPackage.getPackageName());
                            touristInfo.setMainDataId(touristPrice.getValue());
                            touristInfo.setTouristTypeName(touristPrice.getLabel());
                            touristInfo.setPeopleType(1);
                            touristInfo.setGroupFee(groupAddFee);
                            touristInfo.setNoshow(0);
                            touristInfo.setLockStatus(0);
                            touristInfo.setPayStatus(1);
                            touristInfo.setBuyVisa(0);
                            touristInfo.setBuyInsurance(0);
                            touristInfo.setCollectionFee(BigDecimal.ZERO);
                            touristInfo.setTotalPaidIn(BigDecimal.ZERO);
                            touristInfo.setRefundAmount(BigDecimal.ZERO);
                            //总应收
                            BigDecimal totalReceivables = groupAddFee;
                            if (CollectionUtils.isNotEmpty(collectionTouristList)){
                                for (CollectionTouristPriceDTO collectionPrice : collectionTouristList){
                                    if (collectionPrice.getTouristTypeId().longValue() == touristPrice.getValue().longValue()){
                                        List<TouristCollectionItemDTO> collectionItemList = collectionPrice.getCollectionItemList();
                                        if (CollectionUtils.isNotEmpty(collectionItemList)){
                                            //旅客代收费用明细
                                            List<TouristCollectionFeeJson> collectionFeeJsonList = new ArrayList<>();
                                            for (TouristCollectionItemDTO itemDTO : collectionItemList){
                                                TouristCollectionFeeJson collectionFeeJson = EntityUtil.copy(itemDTO,TouristCollectionFeeJson.class);
                                                collectionFeeJson.setTotalAmount(itemDTO.getTotalAmount().multiply(itemDTO.getExchangeRate()).setScale(2,BigDecimal.ROUND_HALF_UP));
                                                collectionFeeJsonList.add(collectionFeeJson);
                                            }
                                            if (collectionFeeJsonList.size() > 0){
                                                touristInfo.setCollectionFeeJson(JSON.toJSONString(collectionFeeJsonList));
                                            }
                                        }
                                        totalReceivables = totalReceivables.add(collectionPrice.getPrice());
                                        touristInfo.setCollectionFee(collectionPrice.getPrice());
                                        break;
                                    }
                                }
                            }
                            touristInfo.setTotalReceivables(totalReceivables);
                            touristInfo.setAdjustmentCost(adjustmentCost);
                            touristInfo.setOtherAmount(BigDecimal.ZERO);
                            touristInfo.setReceiptedAmount(BigDecimal.ZERO);
                            touristInfo.setRemainingReceivables(totalReceivables);
                            touristInfo.setIsFullInfo(0);
                            touristInfo.setCreateId(userId);
                            touristInfo.setGmtCreate(LocalDateTime.now());
                            touristInfo.setIsDeleted(0);
                            touristInfoList.add(touristInfo);
                        }
                        //定制包团订单游客自由报价
                        CustomizedOrderTouristPrice orderTouristPrice = new CustomizedOrderTouristPrice();
                        orderTouristPrice.setId(SnowflakeIdWorker.nextId());
                        orderTouristPrice.setOrderId(order.getId());
                        orderTouristPrice.setPackageId(reqPackage.getId());
                        orderTouristPrice.setPackageName(reqPackage.getPackageName());
                        orderTouristPrice.setMainDataId(touristPrice.getValue());
                        orderTouristPrice.setName(touristPrice.getLabel());
                        orderTouristPrice.setPeopleNum(touristPrice.getPeopleNum());
                        orderTouristPrice.setSort(touristPrice.getSort());
                        orderTouristPrice.setAgeBegin(touristPrice.getAgeBegin());
                        orderTouristPrice.setAgeEnd(touristPrice.getAgeEnd());
                        orderTouristPrice.setSinglePrice(groupAddFee);
                        orderTouristPrice.setTotalPrice(groupAddFee.multiply(new BigDecimal(touristPrice.getPeopleNum())));
                        orderTouristPrice.setCreateId(userId);
                        orderTouristPrice.setGmtCreate(LocalDateTime.now());
                        orderTouristPrice.setIsDeleted(0);
                        orderTouristPriceList.add(orderTouristPrice);
                    }
                }
            }
        }else{
            //行程报价
            //行程报价-总单价
            BigDecimal quoteTotalSinglePrice = tripSchedule.getQuoteTotalSinglePrice();
            quoteTotalSinglePrice = tripScheduleService.getScheduleAddAmount(quoteTotalSinglePrice,req.getScheduleId(),userId);
            if (quoteTotalSinglePrice != null){
                totalTourFee = totalTourFee.add(quoteTotalSinglePrice.multiply(new BigDecimal(totalPeople)));
            }
            //旅客信息
            for (QuotationTouristTypeReq tourist : touristList){
                if (tourist.getPeopleNum() > 0){
                    for (int i=0;i<tourist.getPeopleNum();i++){
                        CustomizedOrderTouristInfo touristInfo = new CustomizedOrderTouristInfo();
                        touristInfo.setId(SnowflakeIdWorker.nextId());
                        touristInfo.setOrderId(order.getId());
                        touristInfo.setScheduleId(req.getScheduleId());
                        touristInfo.setMainDataId(tourist.getValue());
                        touristInfo.setTouristTypeName(tourist.getLabel());
                        touristInfo.setPayStatus(1);
                        touristInfo.setGroupFee(quoteTotalSinglePrice);
                        touristInfo.setPayStatus(1);
                        touristInfo.setBuyVisa(0);
                        touristInfo.setBuyInsurance(0);
                        touristInfo.setCollectionFee(BigDecimal.ZERO);
                        touristInfo.setTotalPaidIn(BigDecimal.ZERO);
                        touristInfo.setRefundAmount(BigDecimal.ZERO);
                        BigDecimal totalReceivables = quoteTotalSinglePrice;
                        if (collectionTouristList != null && collectionTouristList.size() > 0){
                            for (CollectionTouristPriceDTO collectionPrice : collectionTouristList){
                                if (collectionPrice.getTouristTypeId().longValue() == tourist.getValue().longValue()){
                                    totalReceivables = totalReceivables.add(collectionPrice.getPrice());
                                    touristInfo.setCollectionFee(collectionPrice.getPrice());
                                    break;
                                }
                            }
                        }
                        touristInfo.setTotalReceivables(totalReceivables);
                        //调整费用
                        touristInfo.setAdjustmentCost(adjustmentCost);
                        touristInfo.setOtherAmount(BigDecimal.ZERO);
                        touristInfo.setReceiptedAmount(BigDecimal.ZERO);
                        touristInfo.setRemainingReceivables(totalReceivables);
                        touristInfo.setIsFullInfo(0);
                        touristInfo.setCreateId(userId);
                        touristInfo.setGmtCreate(LocalDateTime.now());
                        touristInfo.setIsDeleted(0);
                        touristInfoList.add(touristInfo);
                    }
                }
            }
        }
        totalPrice = totalTourFee.add(totalCollectionFee);
        //订单号
        String orderNo = numberService.getOrderNumber(userId);
        order.setOrderNumber(orderNo);
        order.setTotalPrice(totalPrice);
        order.setPlaceOrderStatus(1);
        order.setOrderType(1);
        order.setCreateId(userId);
        order.setGmtCreate(LocalDateTime.now());
        order.setIsDeleted(0);
        /**
         * 生成订单
         */
        int insert = orderMapper.insert(order);
        if (insert <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        //新增订单金额统计
        CustomizedOrderAmountStatistics amountStatistics = new CustomizedOrderAmountStatistics();
        amountStatistics.setId(SnowflakeIdWorker.nextId());
        amountStatistics.setOrderId(order.getId());
        amountStatistics.setScheduleId(req.getScheduleId());
        amountStatistics.setTotalReceivables(order.getTotalPrice());
        amountStatistics.setTotalPaidIn(BigDecimal.ZERO);
        amountStatistics.setRemainingReceivables(order.getTotalPrice());
        amountStatistics.setRefundAmount(BigDecimal.ZERO);
        amountStatistics.setTotalTourFee(totalTourFee);
        amountStatistics.setCollectionFee(totalCollectionFee);
        amountStatistics.setAdjustmentCost(BigDecimal.ZERO);
        amountStatistics.setOtherAmount(BigDecimal.ZERO);
        amountStatistics.setReceiptedAmount(BigDecimal.ZERO);
        int insertStatistics = orderAmountStatisticsMapper.insert(amountStatistics);
        //批量新增旅客信息
        if (touristInfoList.size() > 0){
            Integer infoBatch = orderTouristInfoMapper.insertBatchSomeColumn(touristInfoList);
            if (infoBatch < touristInfoList.size()){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //批量新增游客自由报价
        if (orderTouristPriceList.size() > 0){
            Integer priceBatch = orderTouristPriceMapper.insertBatchSomeColumn(orderTouristPriceList);
            if (priceBatch < orderTouristPriceList.size()){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        if (insertStatistics <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        //更新团期已下单金额
        Integer updateAmountStatistics = tripScheduleAmountStatisticsService.updateAmountStatistics(
                new TripScheduleAmountStatisticsReq(req.getScheduleId(),totalTourFee,totalPeople,userId,1));
        if (updateAmountStatistics <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(order.getId());
    }

    /**
     * 计算调整费用
     * @param feeAdjustList
     * @return
     */
    private BigDecimal getAdjustmentFee(List<TripScheduleFeeAdjustDTO> feeAdjustList) {
        BigDecimal adjustmentCost = BigDecimal.ZERO;
        if (feeAdjustList != null && feeAdjustList.size() > 0){
            for (TripScheduleFeeAdjustDTO dto : feeAdjustList) {
                if (dto.getAdjustType().intValue() == NumberConstant.ONE.getValue()){
                    //增加
                    adjustmentCost = adjustmentCost.add(dto.getCostAmount());
                }else{
                    //扣减
                    adjustmentCost = adjustmentCost.subtract(dto.getCostAmount());
                }
            }
        }
        return adjustmentCost;
    }

    /**
     * 订单列表
     *
     * @param req
     * @return
     */
    @Override
    public Result<CustomOrderListDTO> list(CustomOrderListReq req, TokenUser currentUser) {
        Result<List<Long>> permissionResult = sysPermissionService.queryPermission(req.getMenuId(), currentUser.getId());
        //TODO 权限校验
        if (!permissionResult.isSuccess()) {
            SystemError result = SystemError.getDefined(permissionResult.getCode());
            throw new BusinessException(result);
        }
        //权限检验
        boolean permision = true;
        if (!GlobalConstants.Role.isAdmin(currentUser.getUsername())){
            permision = false;
        }
        //订单列表
        CustomOrderListDTO customOrderListDTO = orderMapper.selectCountBySelective(req);
        if (customOrderListDTO == null){
            customOrderListDTO = new CustomOrderListDTO();
        }
        IPage<CustomOrderListReq> page = new Page<>(req.getPageNo(), req.getPageSize());
        IPage<CustomOrderPageDTO> customOrderDTOIPage = orderMapper.selectListBySelective(page, req,permision,permissionResult.getData());
        List<CustomOrderPageDTO> records = customOrderDTOIPage.getRecords();
        List<Long> listId = new ArrayList<>();
        for (CustomOrderPageDTO record : records) {
            if(record.getScheduleId() != null) {
                listId.add(record.getScheduleId());
            }
        }
        if (records.size() > 0) {
            TripScheduleListIdReq tripScheduleListIdReq = new TripScheduleListIdReq();
            tripScheduleListIdReq.setListId(listId);
            //查询指定id集团期
            List<TripScheduleListDTO> tripScheduleList = tripScheduleService.getTripScheduleList(tripScheduleListIdReq);
            for (CustomOrderPageDTO record : records) {
                for (TripScheduleListDTO tripScheduleListDTO : tripScheduleList) {
                    if (Objects.equals(record.getScheduleId(),tripScheduleListDTO.getId())){
                        record.setBigClientName(tripScheduleListDTO.getBigClientName());
                        record.setTripTitle(tripScheduleListDTO.getName());
                        record.setTripNumber(tripScheduleListDTO.getTripNumber());
                        record.setDepartDate(tripScheduleListDTO.getDepartureDate());
                        if (tripScheduleListDTO.getDepartureDate() != null){
                            String departureWeekDay = CharUtil.getWeekDay(tripScheduleListDTO.getDepartureDate().getDayOfWeek().getValue());
                            record.setDepartureWeekDay(departureWeekDay);
                        }
                        record.setScheduleStatus(tripScheduleListDTO.getGroupStatus());
                        UserDTO saler = sysUserService.loadUserByParam(record.getCreateId(), 1);
                        if (saler != null){
                            record.setSalespersonName(saler.getFullName());
                            record.setSalespersonDept(saler.getDept());
                        }
                        //收客情况
                        List<CustomOrderPageTouristPeopleDTO> touristPeopleList = orderTouristInfoMapper.queryTouristByType(record.getId());
                        if (touristPeopleList != null && touristPeopleList.size() > 0){
                            record.setTouristPeopleList(touristPeopleList);
                        }
                        if (Objects.equals(record.getScheduleId(), tripScheduleListDTO.getId())) {
                            //未收提示判断
                            LocalDateTime orderDateTime = OrderUtil.asLocalDateTime(record.getGmtCreate());
                            if (record.getRemainingReceivables().compareTo(new BigDecimal(0)) > 0){
                                //未收金额大于0
                                //交余款天数
                                Integer deliveryDays = tripScheduleListDTO.getDeliveryDays();
                                //最晚交余款时间
                                LocalDateTime deliveryTime = orderDateTime.plusDays(deliveryDays);
                                record.setDeliveryTime(deliveryTime);
                                if (LocalDateTime.now().isBefore(deliveryTime)){
                                    record.setDeliveryStatus(1);
                                }else{
                                    record.setDeliveryStatus(2);
                                }
                            }
                            if (record.getTotalPaidIn().compareTo(new BigDecimal(0)) == 0) {
                                if (orderDateTime.compareTo(LocalDateTime.now()) > 0) {
                                    record.setRemainingReceivablesRemark(orderDateTime.format(DateTimeFormatter.ofPattern(OrderUtil.HH_mm_ss)) + " 前付款");
                                }
                            }
                            if (record.getTotalPaidIn().compareTo(new BigDecimal(0)) > 0) {
                                if (orderDateTime.compareTo(LocalDateTime.now()) > 0) {
                                    record.setRemainingReceivablesRemark(orderDateTime.format(DateTimeFormatter.ofPattern(OrderUtil.yyyy_MM_dd)) + " 前付款");
                                }
                            }
                        }
                    }
                }
            }
        }
        PageResponse<CustomOrderPageDTO> customOrderDTOPage = new PageResponse<>(records,
                customOrderDTOIPage.getCurrent() == 1,
                customOrderDTOIPage.getTotal() <= (customOrderDTOIPage.getCurrent() * customOrderDTOIPage.getSize()),
                customOrderDTOIPage.getTotal(), customOrderDTOIPage.getCurrent(),
                customOrderDTOIPage.getSize());
        customOrderListDTO.setPage(customOrderDTOPage);
        return Result.success(customOrderListDTO);
    }

    /**
     * 取消订单
     *
     * @param req
     * @return
     */
    @Override
    public Result cancel(CustomOrderIdReq req) {
        QueryWrapper<CustomizedOrderAmountStatistics> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomizedOrderAmountStatistics::getOrderId, req.getId());
        CustomizedOrderAmountStatistics dbStatistics = orderAmountStatisticsMapper.selectOne(queryWrapper);
        //已有收款订单不能取消
        if (dbStatistics.getTotalPaidIn().compareTo(new BigDecimal(0)) > 0) {
            throw new BusinessException(SystemError.CUSTOM_ORDER_4034);
        }
        //获取订单
        CustomizedOrder order = orderMapper.selectById(req.getId());
        if (order == null || Objects.equals(order.getIsDeleted(),NumberConstant.ONE.getValue())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4008);
        }
        order.setModifiedId(req.getUserId());
        order.setIsDeleted(IsDeletedCode.YES.getCode());
        //修改订单
        boolean update = updateById(order);
        if (!update){
            throw new BusinessException(SystemError.SYS_437);
        }
        //取消订单后的处理
        dealAfterOrderCancel(req.getId(),req.getUserId(),order.getScheduleId(),dbStatistics.getId(),order.getTotalPeople(),dbStatistics.getTotalTourFee());
        return Result.success();
    }

    /**
     * 取消订单后的处理
     * @param orderId
     * @param userId
     * @param scheduleId
     * @param statisticsId
     * @param totalPeople
     * @param totalTourFee
     */
    private void dealAfterOrderCancel(Long orderId, Long userId, Long scheduleId, Long statisticsId,Integer totalPeople,BigDecimal totalTourFee) {
        //团期旅客类型统计回滚
        List<MainDataCount> list =  orderTouristInfoMapper.queryCountByMainDataId(orderId);
        boolean blCount = tripScheduleTouristCountService.rollBackCount(list,scheduleId,userId);
        //清空订单折扣记录
        boolean blDiscount = orderDiscountService.cleanByOrder(orderId,userId);
        //清空关联旅客
        boolean blTourist = orderTouristInfoService.cleanByOrder(orderId,userId);
        //清空订单统计
        int del = orderAmountStatisticsMapper.deleteById(statisticsId);
        //清空报价
        boolean blPrice = orderTouristPriceService.cleanByOrder(orderId,userId);
        //团期金额统计回滚
        boolean rollBack = tripScheduleAmountStatisticsService.rollBackStatistics(scheduleId, totalPeople,totalTourFee,userId);
        if (!blDiscount || del <= 0 || !blTourist || !blPrice || !rollBack || !blCount){
            throw new BusinessException(SystemError.SYS_437);
        }
    }

    /**
     * 订单详情
     *
     * @param req
     * @return
     */
    @Override
    public Result<CustomOrderDetailDTO> detail(CustomOrderIdReq req) {
        //订单详情
        CustomOrderDetailDTO dto = orderMapper.selectDetailBySelective(req);
        //团期信息
        if (dto.getScheduleId() != null){
            CustomizedTripScheduleDTO tripSchedule = tripScheduleService.queryByScheduleId(dto.getScheduleId());
            if (tripSchedule == null){
                throw new BusinessException(SystemError.CUSTOM_3006);
            }
            dto.setTripNumber(tripSchedule.getTripNumber());
            dto.setTripTitle(tripSchedule.getName());
            dto.setTripSubtitle(tripSchedule.getSubtitle());
            dto.setDeparturePlace(tripSchedule.getDeparturePlace());
            dto.setDestination(tripSchedule.getDestination());
            dto.setChargePersonName(tripSchedule.getChargePersonName());
            UserDTO userDTO = sysUserService.queryCacheUser(tripSchedule.getChargePersonId());
            if (userDTO != null){
                dto.setChargePersonDept(userDTO.getDept());
            }
            //出发日期
            if (tripSchedule.getDepartureDate() != null){
                dto.setDepartureDate(tripSchedule.getDepartureDate().toLocalDate());
                dto.setDepartureWeekDay(CharUtil.getWeekDay(tripSchedule.getDepartureDate().getDayOfWeek().getValue()));
                LocalDateTime returnDate = tripSchedule.getDepartureDate().plusDays((long)tripSchedule.getTravelDays());
                dto.setReturnDate(returnDate.toLocalDate());
                dto.setReturnWeekDay(CharUtil.getWeekDay(returnDate.getDayOfWeek().getValue()));
            }
        }
        //套餐信息
        List<OrderTouristPriceDTO> touristPriceList = orderTouristPriceMapper.queryListByPackage(req.getId());
        dto.setTouristPriceList(touristPriceList);
        if (CollectionUtils.isEmpty(touristPriceList)){
            //行程报价统计订单人数
            List<CustomOrderPageTouristPeopleDTO> touristPeopleList = orderTouristInfoMapper.countByTouristType(req.getId());
            dto.setTouristPeopleList(touristPeopleList);
        }
        return Result.success(dto);
    }

    /**
     * 操作订单-修改联络人信息
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<CustomOrderUpdateContactDTO> updateContact(CustomOrderUpdateContactReq req) {
        CustomizedOrder order = getById(req.getOrderId());
        if (order == null || Objects.equals(order.getIsDeleted(),1)){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4008);
        }
        order = EntityUtil.copy(req,CustomizedOrder.class);
        order.setId(req.getOrderId());
        order.setModifiedId(req.getUserId());
        boolean update = updateById(order);
        if (!update){
            throw new BusinessException(SystemError.SYS_437);
        }
        CustomOrderUpdateContactDTO dto = EntityUtil.copy(order,CustomOrderUpdateContactDTO.class);
        return Result.success(dto);
    }

    @Override
    public Result<List<MyCustomizedOrderDTO>> recentToNow(LocalDateTime recent, LocalDateTime now) {
        List<CustomizedOrder> orderList = baseMapper.selectList(Wrappers.<CustomizedOrder>lambdaQuery()
                .eq(CustomizedOrder::getIsDeleted, IsDeletedCode.NO.getCode())
                .ge(recent != null, CustomizedOrder::getGmtModified, recent)
                .le(CustomizedOrder::getGmtModified, now));

        return Result.success(EntityUtil.copyList(orderList, MyCustomizedOrderDTO.class));
    }


}
